/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package paquetevistas.almacen;

import Seguridad.Controlador.controladorseguridad;
import controlador.almacen.controladoralmacen;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
import modelos.Motivo;
import modelos.Movimiento;
import modelos.Producto;
import modelos.ProductoxmovimientoId;
import modelos.Usuario;
import paquetevistas.Escritorio;

/**
 *
 * @author mariofcandia
 */
public class InventarioNuevo extends javax.swing.JInternalFrame {

    /**
     * Creates new form InventarioNuevo
     */
    ProductTableModel myProductTableModel = new ProductTableModel();
    public static controladoralmacen mycontroladoralmacen = new controladoralmacen();
    
    //Para el registro de Log
    public static Usuario usuario = lbj.LBJ.Login.usuario;
    public static controladorseguridad mycontroladorseguridad = new controladorseguridad();

    class ProductTableModel extends AbstractTableModel {

        List<Producto> pro = new ArrayList<Producto>();
        ArrayList<String> lista3 = new ArrayList<String>();
        //ArrayList<String> array3 = new ArrayList<String>();

        public ProductTableModel() {
            modelos.Almacen almacen = lbj.LBJ.Login.escritorio.inventario.almaceninventario;
            pro = mycontroladoralmacen.sacaproductosbyalmacen(almacen);
            //pro = mycontroladoralmacen.sacaproductos();
            for (int i = 0; i < pro.size(); i++) {
                lista3.add("" + pro.get(i).getStock());
            }
        }
        String[] titles = {"Producto", "Tipo", "Unidad", "Stock", "Stock Real"};

        public int getRowCount() {
            return pro.size();
        }

        public int getColumnCount() {
            return 5;
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            String res = null;
            int tipo;
            int unidad;
            String unidadnombre = null;
            String nombre = null;
            Producto p = pro.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    res = p.getNombre();
                    break;
                case 1:
                    tipo = p.getTipoproducto().getIdtipoproducto();
                    nombre = mycontroladoralmacen.sacanombretipo(tipo);
                    res = nombre;
                    break;
                case 2:
                    unidad = p.getUnidadmedida().getIdunidadmedida();
                    unidadnombre = mycontroladoralmacen.sacanombreunidad(unidad);
                    res = unidadnombre;
                    break;
                case 3:
                    res = "" + p.getStock();
                    break;
                case 4:
                    res = lista3.get(rowIndex);
                    break;
            }
            return res;
        }

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            if (columnIndex == 4) {
                return true;
            }
            return false;
        }

        public void setValueAt(Object value, int row, int col) {
            String cadena = value.toString();
            lista3.set(row, cadena);
        }

        public String getColumnName(int col) {
            return titles[col];
        }
    }

    public InventarioNuevo() {
        initComponents();
        loadComponents();
    }

    public void loadComponents() {
        modelos.Almacen almacen = lbj.LBJ.Login.escritorio.inventario.almaceninventario;
        jTextField1.setText(almacen.getNombre());
        jTable1.setModel(myProductTableModel);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jTextField1 = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();

        setClosable(true);
        setTitle("Gestionar Inventario");

        jTextField1.setEditable(false);
        jTextField1.setText("Almacen Principal");
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"Azucar", "MP", "Kg", "400", "410"},
                {"Arina", "MP", "Kg", "300", "315"},
                {"Relleno", "Insumo", "Kg", "300", "300"},
                {null, null, null, null, null}
            },
            new String [] {
                "Producto", "Tipo", "Unidad", "Stock", "Stock Real"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE)
        );

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/save.png"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Grabar");

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/prev 2.png"))); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel2.setText("Regresar");

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/refresh.png"))); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel3.setText("Refrescar");

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(34, 34, 34)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jButton2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 46, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel2)))
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(26, 26, 26)
                        .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 46, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel1)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jButton3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 46, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel3))
                .add(29, 29, 29))
            .add(jPanel1Layout.createSequentialGroup()
                .add(26, 26, 26)
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jButton3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 46, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel3)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jButton2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 46, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jLabel2))
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 46, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 16, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        int compra = 0;
        int venta = 0;
        int correcto = mycontroladoralmacen.verificanumeros2(myProductTableModel.lista3);
        if (correcto == 1) {
            JOptionPane.showMessageDialog(this, "Ingrese el stock real");
        } else if (correcto == 2) {
            JOptionPane.showMessageDialog(this, "Ingrese valores numericos positivos");
        } else {
            Motivo motivo = new Motivo();
            motivo = mycontroladoralmacen.sacamotivobyid(6);
            Date fechahoy = new Date();
            modelos.Almacen alma = lbj.LBJ.Login.escritorio.inventario.almaceninventario;
            List<Producto> productosentrada = new ArrayList<Producto>();
            ArrayList<Float> productosentradacantidad = new ArrayList<Float>();
            List<Producto> productossalida = new ArrayList<Producto>();
            ArrayList<Float> productossalidacantidad = new ArrayList<Float>();

            for (int i = 0; i < myProductTableModel.pro.size(); i++) {
                float cantidad = Float.parseFloat(myProductTableModel.lista3.get(i));
                Producto p = mycontroladoralmacen.sacaproductobyid(myProductTableModel.pro.get(i).getIdproducto());
                System.out.print(p.getStock() + " ");
                System.out.println(cantidad);
                if (cantidad > p.getStock()) { // va a ser una entrada al almacen xq hay mas stock
                    System.out.print(p.getStock() + " ");
                System.out.println(cantidad);
                    productosentrada.add(p);
                    productosentradacantidad.add(Float.parseFloat(myProductTableModel.lista3.get(i)));
                } else if(cantidad < p.getStock()){//va a ser una salida de almacen xq hay menos stock
                    System.out.print(p.getStock() + " ");
                System.out.println(cantidad);
                    productossalida.add(p);
                    productossalidacantidad.add(Float.parseFloat(myProductTableModel.lista3.get(i)));
                }
            }
            if (productosentrada.size() > 0) {
                mycontroladoralmacen.guardamovimiento(1, alma, motivo, fechahoy, 1,compra, venta);
                Movimiento movimiento = mycontroladoralmacen.sacaultimomovimiento();
                for(int j=0; j<productosentrada.size();j++){
                    ProductoxmovimientoId pxm = new ProductoxmovimientoId();
                    pxm.setIdmovimiento(movimiento.getIdmovimiento());
                    pxm.setIdproducto(productosentrada.get(j).getIdproducto());
                    float cantidad = productosentradacantidad.get(j);
                    Date fechavencimiento = new Date();
                    fechavencimiento.setMonth(fechavencimiento.getMonth() + 1);
                    mycontroladoralmacen.guardaproductoxmovimiento(pxm, movimiento, productosentrada.get(j), cantidad - productosentrada.get(j).getStock(), fechavencimiento);
                    //aqui cambia el stock del producto
                    Producto p = productosentrada.get(j);
                    Float stock = cantidad;// + p.getStock();
                    mycontroladoralmacen.actualizarstock(p, stock);
                }
                
                mycontroladorseguridad.insertarlog(usuario, new Date(), "Insertar", "Movimiento", "Insertar Movimiento");
                mycontroladorseguridad.insertarlog(usuario, new Date(), "Insertar", "Productoxmovimiento", "Insertar Productoxmovimiento");
            }
            if(productossalida.size() > 0){
                mycontroladoralmacen.guardamovimiento(2, alma, motivo, fechahoy, 1, compra, venta);
                Movimiento movimiento = mycontroladoralmacen.sacaultimomovimiento();
                for(int k=0; k<productossalida.size(); k++){
                    ProductoxmovimientoId pxm = new ProductoxmovimientoId();
                    pxm.setIdmovimiento(movimiento.getIdmovimiento());
                    pxm.setIdproducto(productossalida.get(k).getIdproducto());
                    float cantidad = productossalidacantidad.get(k);
                    Date fechavencimiento = new Date();
                    fechavencimiento.setMonth(fechavencimiento.getMonth() + 1);
                    mycontroladoralmacen.guardaproductoxmovimiento(pxm, movimiento, productossalida.get(k), productossalida.get(k).getStock() - cantidad, fechavencimiento);
                    //aqui cambia el stock del producto
                    Producto p = productossalida.get(k);
                    Float stock = cantidad;
                    mycontroladoralmacen.actualizarstock(p, stock);
                }
                
                mycontroladorseguridad.insertarlog(usuario, new Date(), "Insertar", "Movimiento", "Insertar Movimiento");
                mycontroladorseguridad.insertarlog(usuario, new Date(), "Insertar", "Productoxmovimiento", "Insertar Productoxmovimiento");
            }
            this.dispose();
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        Escritorio.inventario.setVisible(true);
        this.setVisible(false);
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        for (int i = 0; i < myProductTableModel.pro.size(); i++) {
            myProductTableModel.lista3.set(i, "" + myProductTableModel.pro.get(i).getStock());
        }
        myProductTableModel.fireTableChanged(null);
    }//GEN-LAST:event_jButton3ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
